//创建用户相关的小仓库
import { defineStore } from 'pinia'
//引入接口
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
//引入数据类型
import type {
  loginFormData,
  loginResponseData,
  userInfoResponseData,
  logoutResponseData
} from '@/api/user/type'
import type { UserState } from './types/type'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
//引入路由（常量路由）
import { constantRoute, asyncRoute, anyRoute } from '@/router/routes'
import router from '@/router'
//引入深拷贝方法
//@ts-ignore
import cloneDeep from 'lodash/cloneDeep'

//用于过滤当前用户需要展示的异步路由
function filterAsyncRoute(asyncRoute: any, routes: any) {
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}

//初始化路由器
function setRouter(router: any) {
  router.clearRoutes()
  constantRoute.forEach((route: any) => {
    router.addRoute(route)
  })
}

//创建用户小仓库
let useUserStore = defineStore('User', {
  //存储数据的地方
  state: (): UserState => {
    return {
      token: GET_TOKEN(), //用用户唯一标识token
      menuRoutes: constantRoute, //仓库存储生成菜单需要的数组（路由）
      username: '',
      avatar: '',
      buttons: [] //存储当前用户是否包含某一个按钮
    }
  },
  //异步、逻辑的地方
  actions: {
    async userLogin(data: loginFormData) {
      let result: loginResponseData = await reqLogin(data)
      //成功200
      //失败201
      if (result.code == 200) {
        this.token = result.data as string
        SET_TOKEN(result.data as string)
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
    async userInfo() {
      let result: userInfoResponseData = await reqUserInfo()

      if (result.code == 200) {
        this.username = result.data.name
        this.avatar = result.data.avatar
        this.buttons = result.data.buttons
        //计算当前用户需要展示的异步路由
        let userAsyncRoute = filterAsyncRoute(cloneDeep(asyncRoute), result.data.routes)
        this.menuRoutes = [...constantRoute, ...userAsyncRoute, ...anyRoute]
        //目前路由器管理的只有常量路由，用户计算完毕的异步路由和任意路由需要动态追加
        let dongtaiRoute = [...userAsyncRoute, ...anyRoute]
        dongtaiRoute.forEach((route: any) => {
          router.addRoute(route)
        })
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    async userLogout() {
      //向退出登录的接口发请求（通知服务器本次用户唯一标识失效）
      let result: logoutResponseData = await reqLogout()
      if (result.code == 200) {
        this.token = ''
        this.username = ''
        this.avatar = ''
        this.menuRoutes = constantRoute
        //初始化路由器
        setRouter(router)
        //还需要清除本次存储的token
        REMOVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    }
  },
  //计算属性
  getters: {}
})

//对外暴露获取小仓库方法
export default useUserStore
